package com.atguigu.gilimall.thirdpart.utils;


import com.alibaba.fastjson.JSONObject;
import com.aliyun.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.dysmsapi20170525.models.SendSmsResponse;
import com.aliyun.teaopenapi.models.Config;

import java.text.DecimalFormat;
import java.util.*;

/** 阿里云短信服务
 * @Author ShiJieLin
 * @Date 2022/3/12 10:10
 * @Version 1.0
 */
public class SmsUtil {

    private static final String accessKeyId = "LTAI4GH7FydjHhZTBMaHo6GW";
    private static final String accessKeySecret = "08mAmxn0JKnWiyW0exPGnyOciOv7ut";
    private static final Random random = new Random();

    private static final DecimalFormat fourdf = new DecimalFormat("0000");

    private static final DecimalFormat sixdf = new DecimalFormat("000000");



    public static com.aliyun.dysmsapi20170525.Client createClient() throws Exception {
        Config config = new Config()
                // 您的AccessKey ID
                .setAccessKeyId(accessKeyId)
                // 您的AccessKey Secret
                .setAccessKeySecret(accessKeySecret);
        // 访问的域名
        config.endpoint = "dysmsapi.aliyuncs.com";
        return new com.aliyun.dysmsapi20170525.Client(config);
    }

    public static SendSmsResponse createSms(String phone, Map<String, Object> code) throws Exception {

        SendSmsRequest sendSmsRequest = new SendSmsRequest()
                .setSignName("阿里云短信测试")
                .setTemplateCode("SMS_154950909")
                .setPhoneNumbers(phone)
                .setTemplateParam(JSONObject.toJSONString(code));
        //
        SendSmsResponse response = createClient().sendSms(sendSmsRequest);

        return response;
    }

    /**
     * 给定数组，抽取n个数据
     * @param list
     * @param n
     * @return
     */
    private static ArrayList getRandom(List list, int n) {

        Random random = new Random();

        HashMap<Object, Object> hashMap = new HashMap<Object, Object>();

        // 生成随机数字并存入HashMap
        for (int i = 0; i < list.size(); i++) {

            int number = random.nextInt(100) + 1;

            hashMap.put(number, i);
        }

        // 从HashMap导入数组
        Object[] robjs = hashMap.values().toArray();

        ArrayList r = new ArrayList();

        // 遍历数组并打印数据
        for (int i = 0; i < n; i++) {
            r.add(list.get((int) robjs[i]));
            System.out.print(list.get((int) robjs[i]) + "\t");
        }
        System.out.print("\n");
        return r;
    }

    /** 获取四位数验证码
     * @return
     */
    public static String getFourBitRandom() {
        return fourdf.format(random.nextInt(10000));
    }

    /** 获取六位数验证码
     * @return
     */
    public static String getSixBitRandom() {
        return sixdf.format(random.nextInt(1000000));
    }
}
